﻿using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Collections.Generic;

namespace BoardPACUtil.Security
{
    public class HeaderBehavior : IEndpointBehavior
    {
        private Dictionary<string, string> headers;

        public HeaderBehavior(Dictionary<string, string> headers)
        {
            this.headers = headers;
        }

        public void AddBindingParameters(ServiceEndpoint serviceEndpoint,
            System.ServiceModel.Channels
            .BindingParameterCollection bindingParameters) { }

        public void ApplyClientBehavior(ServiceEndpoint serviceEndpoint,
            System.ServiceModel.Dispatcher.ClientRuntime behavior)
        {
            behavior.MessageInspectors.Add(new HeaderMessageInspector(headers));
        }

        public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint,
            System.ServiceModel.Dispatcher
            .EndpointDispatcher endpointDispatcher) { }

        public void Validate(ServiceEndpoint serviceEndpoint) { }
    }

    public class HeaderMessageInspector : IClientMessageInspector
    {
        private Dictionary<string, string> headers;

        public HeaderMessageInspector(Dictionary<string, string> headers)
        {
            this.headers = headers;
        }

        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply,
            object correlationState) { }

        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request,
            System.ServiceModel.IClientChannel channel)
        {
            HttpRequestMessageProperty httpRequestMessage;
            object httpRequestMessageObject;
            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name
                , out httpRequestMessageObject))
            {
                httpRequestMessage = httpRequestMessageObject
                    as HttpRequestMessageProperty;
                foreach (KeyValuePair<string, string> item in headers)
                {
                    if (string.IsNullOrEmpty(httpRequestMessage.Headers[item.Key]))
                    {
                        httpRequestMessage.Headers[item.Key] = item.Value;
                    } 
                }
            }
            else
            {
                httpRequestMessage = new HttpRequestMessageProperty();
                foreach (KeyValuePair<string, string> item in headers)
                {
                    httpRequestMessage.Headers.Add(item.Key, item.Value); 
                }
                request.Properties.Add(HttpRequestMessageProperty.Name
                    , httpRequestMessage);
            }

            return null;
        }
    }
}
